#!/bin/bash

# Release Manager Script
# Comprehensive script for managing releases

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(dirname "$SCRIPT_DIR")"

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# Functions
show_help() {
    cat << EOF
${GREEN}=== GoYOLO Release Manager ===${NC}

Usage: $0 <command> [options]

Commands:
  create <version>          Create a new release package
  download-models <type>    Download and convert models
  package <version>         Create release archive
  verify <archive>          Verify release archive
  deploy <archive> <path>   Deploy release to system
  list                      List available releases
  clean                     Clean release directory
  help                      Show this help message

Examples:
  # Create complete release
  $0 create v1.0.0

  # Download YOLOv8 nano model
  $0 download-models yolov8n

  # Verify release archive
  $0 verify release/goyolopenvino-v1.0.0.tar.gz

  # Deploy to /opt/goyolo
  $0 deploy release/goyolopenvino-v1.0.0.tar.gz /opt/goyolo

Supported Models:
  - yolov8n, yolov8s, yolov8m, yolov8l
  - yolov11n, yolov11s, yolov11m

EOF
}

create_release() {
    local version="$1"
    if [ -z "$version" ]; then
        echo -e "${RED}Error: Version required${NC}"
        echo "Usage: $0 create <version>"
        exit 1
    fi
    
    echo -e "${BLUE}Creating release $version...${NC}"
    bash "$SCRIPT_DIR/create-release.sh" "$version"
}

download_models() {
    local model_type="$1"
    if [ -z "$model_type" ]; then
        echo -e "${RED}Error: Model type required${NC}"
        echo "Supported types: yolov8n, yolov8s, yolov8m, yolov8l, yolov11n, yolov11s, yolov11m"
        exit 1
    fi
    
    echo -e "${BLUE}Downloading $model_type model...${NC}"
    bash "$SCRIPT_DIR/download-models.sh" "$PROJECT_ROOT/release/goyolopenvino-v1.0.0/models" "$model_type"
}

package_release() {
    local version="$1"
    if [ -z "$version" ]; then
        echo -e "${RED}Error: Version required${NC}"
        exit 1
    fi
    
    local release_dir="$PROJECT_ROOT/release/goyolopenvino-${version}"
    if [ ! -d "$release_dir" ]; then
        echo -e "${RED}Error: Release directory not found: $release_dir${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}Creating archive...${NC}"
    cd "$PROJECT_ROOT/release"
    tar czf "goyolopenvino-${version}.tar.gz" "goyolopenvino-${version}"
    sha256sum "goyolopenvino-${version}.tar.gz" > "goyolopenvino-${version}.sha256"
    
    echo -e "${GREEN}✓ Archive created${NC}"
    ls -lh "goyolopenvino-${version}.tar.gz"
}

verify_release() {
    local archive="$1"
    if [ -z "$archive" ]; then
        echo -e "${RED}Error: Archive path required${NC}"
        exit 1
    fi
    
    if [ ! -f "$archive" ]; then
        echo -e "${RED}Error: Archive not found: $archive${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}Verifying release...${NC}"
    
    # Check archive integrity
    echo "Checking archive integrity..."
    tar tzf "$archive" > /dev/null
    echo "✓ Archive is valid"
    
    # Check checksum
    local checksum_file="${archive%.tar.gz}.sha256"
    if [ -f "$checksum_file" ]; then
        echo "Verifying checksum..."
        cd "$(dirname "$archive")"
        sha256sum -c "$(basename "$checksum_file")"
        echo "✓ Checksum verified"
    fi
    
    # List contents
    echo ""
    echo "Archive contents:"
    tar tzf "$archive" | head -20
    echo "..."
}

deploy_release() {
    local archive="$1"
    local install_dir="$2"
    
    if [ -z "$archive" ] || [ -z "$install_dir" ]; then
        echo -e "${RED}Error: Archive and install directory required${NC}"
        echo "Usage: $0 deploy <archive> <install_dir>"
        exit 1
    fi
    
    if [ ! -f "$archive" ]; then
        echo -e "${RED}Error: Archive not found: $archive${NC}"
        exit 1
    fi
    
    echo -e "${BLUE}Deploying release...${NC}"
    
    # Extract archive
    local temp_dir=$(mktemp -d)
    tar xzf "$archive" -C "$temp_dir"
    
    # Get release directory name
    local release_name=$(basename "$archive" .tar.gz)
    local release_dir="$temp_dir/$release_name"
    
    # Create install directory
    sudo mkdir -p "$install_dir"
    
    # Copy files
    echo "Copying files..."
    sudo cp -r "$release_dir/bin" "$install_dir/"
    sudo cp -r "$release_dir/config" "$install_dir/"
    sudo cp -r "$release_dir/docs" "$install_dir/"
    sudo cp -r "$release_dir/scripts" "$install_dir/"
    sudo mkdir -p "$install_dir/models"
    
    # Set permissions
    sudo chmod +x "$install_dir/bin"/*
    sudo chmod +x "$install_dir/scripts"/*.sh
    
    # Cleanup
    rm -rf "$temp_dir"
    
    echo -e "${GREEN}✓ Deployment complete${NC}"
    echo "Installation directory: $install_dir"
    echo ""
    echo "Next steps:"
    echo "1. Download models: $install_dir/scripts/download-models.sh"
    echo "2. Configure: nano $install_dir/config/config.env"
    echo "3. Run: $install_dir/scripts/run.sh"
}

list_releases() {
    local release_dir="$PROJECT_ROOT/release"
    
    if [ ! -d "$release_dir" ]; then
        echo "No releases found"
        return
    fi
    
    echo -e "${BLUE}Available releases:${NC}"
    echo ""
    
    cd "$release_dir"
    for archive in *.tar.gz; do
        if [ -f "$archive" ]; then
            local size=$(du -h "$archive" | cut -f1)
            local date=$(stat -f "%Sm" -t "%Y-%m-%d %H:%M:%S" "$archive" 2>/dev/null || stat -c "%y" "$archive" 2>/dev/null | cut -d' ' -f1-2)
            echo "  $archive ($size) - $date"
        fi
    done
}

clean_releases() {
    local release_dir="$PROJECT_ROOT/release"
    
    if [ ! -d "$release_dir" ]; then
        echo "No releases to clean"
        return
    fi
    
    echo -e "${YELLOW}Cleaning release directory...${NC}"
    read -p "Are you sure? (y/N) " -n 1 -r
    echo
    
    if [[ $REPLY =~ ^[Yy]$ ]]; then
        rm -rf "$release_dir"
        echo -e "${GREEN}✓ Cleaned${NC}"
    else
        echo "Cancelled"
    fi
}

# Main
case "${1:-help}" in
    create)
        create_release "$2"
        ;;
    download-models)
        download_models "$2"
        ;;
    package)
        package_release "$2"
        ;;
    verify)
        verify_release "$2"
        ;;
    deploy)
        deploy_release "$2" "$3"
        ;;
    list)
        list_releases
        ;;
    clean)
        clean_releases
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        echo -e "${RED}Unknown command: $1${NC}"
        show_help
        exit 1
        ;;
esac

